const express = require('express');

const routes = express.Router();

//引入md5密码加密中间件
const md5 = require('md5-node');

//引入mysql
const mysql = require('mysql');
//创建连接池
var pool = mysql.createPool({
    connectionLimit : 10,
    host : 'localhost',
    user : 'root',
    password : 'root',
    database : 'personmessage'
})

//设置公共路由
routes.route('/')
    .get((req,resp)=> {
        resp.render('login')
    })
    .post((req,resp)=> {
        //console.log(req.body)
        //获取登录账号
        const uid = req.body.uid.trim();
        //获取登录密码
        const pwd = md5(req.body.pwd.trim());
        //获取登录职务
        const port_id = req.body.select;
        //console.log(name , pwd)
        //清楚空格正常
        // console.log(pwd.length)
    //    执行数据查看   `` : 解析字符串里面的变量
        var sql = `SELECT login.* , permsg.uid FROM login LEFT JOIN permsg ON permsg.id = login.id WHERE login.uid = ${uid} AND login.pwd = '${pwd}' AND login.port_id = ${port_id}`;
        console.log(sql)
        //语句正确
        //console.log(sql)
    //    链接数据库
       pool.getConnection(function(err,connection){
            if(err) throw err;
        //    链接成功
            connection.query(sql,(error,result)=>{

                //console.log(result)
            //    释放连接   关闭数据库
                connection.release();
                //执行成功  还是需要再次判断result是否为空  为空重定向登录页  不为空则进入查询页

                if(result==''){
                    //数据为空
                    resp.redirect('/')
                }else {
                    var loginame = result[0].loginame;
                    //存储数据   cookie
                    //工号
                    resp.cookie('uid',result[0].uid,{maxAge:86400000,httpOnly:true});
                    //职务
                    resp.cookie('port_id',port_id,{maxAge:86400000,httpOnly:true});
                    //把数据库的密码存储进cookie
                    resp.cookie('pwd',pwd,{maxAge:86400000,httpOnly:true});
                    //获取当前时间戳  Date.now()
                    var getTime = new Date().getTime();
                    resp.cookie('getTimes',getTime,{maxAge:86400000,httpOnly:true});
                    //登录账号的用户名
                    resp.cookie('loginame',loginame,{maxAge:86400000,httpOnly:true});
                    //    登录成功  进入查询页
                    resp.redirect('home')
                    //console.log(result)
                }
                //sql语句出错执行报错处理
                if(error) throw error;
            })
        })
    })
//暴露接口
module.exports = routes;